package com.yiren.manager.ctrl.lease;

import java.lang.reflect.InvocationTargetException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.pagehelper.StringUtil;
import com.yiren.core.exception.MyException;
import com.yiren.core.repository.utils.QueryResult;
import com.yiren.core.utils.Favorites;
import com.yiren.core.utils.HTTPResult;
import com.yiren.core.utils.JsonMapperTool;
import com.yiren.core.utils.UUIDGenerator;
import com.yiren.entity.YrElder;
import com.yiren.entity.YrElderBeHospital;
import com.yiren.entity.YrElderPayRecord;
import com.yiren.entity.YrElderWallet;
import com.yiren.entity.YrLease;
import com.yiren.entity.YrLeasePledge;
import com.yiren.entity.YrLeaseRentRecord;
import com.yiren.entity.YrLeaseSupply;
import com.yiren.entity.YrRetreatLease;
import com.yiren.entity.YrStaffInfo;
import com.yiren.manager.ctrl.GenericController;
import com.yiren.manager.form.elder.YrElderBeHospitalForm;
import com.yiren.manager.form.elder.YrElderForm;
import com.yiren.manager.form.elder.YrElderWalletForm;
import com.yiren.manager.form.elder.YrLeaseDetailForm;
import com.yiren.manager.form.lease.YrLeaseForm;
import com.yiren.manager.form.pension.YrLeaseSupplyForm;
import com.yiren.manager.service.iface.department.YrStaffInfoService;
import com.yiren.manager.service.iface.elder.YrElderBeHospitalService;
import com.yiren.manager.service.iface.elder.YrElderService;
import com.yiren.manager.service.iface.elder.YrElderWalletService;
import com.yiren.manager.service.iface.lease.YrLeasePledgeService;
import com.yiren.manager.service.iface.lease.YrLeaseService;
import com.yiren.manager.service.iface.pension.YrLeaseSupplyService;
import com.yiren.manager.task.DateUtil;
import com.yiren.manager.utils.ObjectUtils;

@RequestMapping("lease")
@Controller
public class YrLeaseController extends GenericController<YrLeaseForm, YrLease> {

	@Autowired
	private YrLeaseService selfService;

	@Autowired
	private YrElderBeHospitalService elderBeHospitalService;

	@Autowired
	private YrLeaseSupplyService leaseSupplyService;

	@Autowired
	private YrElderService elderService;

	@Autowired
	private YrElderWalletService elderWalletService;

	@Autowired
	private YrStaffInfoService staffInfoService;

	@Autowired
	private YrLeasePledgeService leasePledgeService;

	// 保存实体
	@RequestMapping("/save")
	@ResponseBody
	public HTTPResult<YrLeaseForm> save(String data) throws Exception {
		HTTPResult<YrLeaseForm> result = new HTTPResult<YrLeaseForm>();
		JsonMapperTool tool = new JsonMapperTool(data);
		YrLeaseForm form = tool.mapper("lease", YrLeaseForm.class);
		if (null == form) {
			throwExp("param.error");
		}
		YrElder elder = elderService.findOne(form.getElderId());
		if(null==elder){
			throwExp("查询不到该老者相关信息");
		}
//		YrElderBeHospital elderBeHospital = null;
		String sqlWhere = "";//"elder_id=?1 AND be_status=0";
//		if (form.getLeaseType() == 1) {// 院内
//			QueryResult<YrElderBeHospital> qrElderBeHospital = elderBeHospitalService.find(YrElderBeHospital.class,
//					sqlWhere, new Object[] { form.getElderId() });
//			if (qrElderBeHospital.getTotalRecord() == 0) {
//				throwExp("查询不到该老者的入住信息");
//			}
//			elderBeHospital = qrElderBeHospital.getResultList().get(0);
//		}

		YrLeasePledge leasePledge = new YrLeasePledge();
		if (StringUtil.isEmpty(form.getLeaseId())) {
			form.setLeaseId(UUIDGenerator.getUUID());
			form.setCreateTime(new Date());
			form.setReturnMoney(Float.valueOf(0));
			form.setOffsetMoney(Float.valueOf(0));
			leasePledge.setLeasePledgeId(UUIDGenerator.getUUID());
			leasePledge.setCreateTime(form.getCreateTime());
			leasePledge.setSubjectRoomId(form.getSubjectRoomId());
			leasePledge.setPayTime(form.getLeaseTime());
		}
		form.setUpdateTime(new Date());
		YrLease entity = ObjectUtils.objectToObject(form, YrLease.class);
		YrElderWallet elderWallet = null;
		YrElderPayRecord elderPayRecord = null;
		// 如果是钱包扣费
		if (form.getPayWay() == 2) {
			sqlWhere = "elder_id=?1";
			QueryResult<YrElderWallet> qrElderWallet = elderWalletService.find(YrElderWallet.class, sqlWhere,
					new Object[] { form.getElderId() });
			if (qrElderWallet.getTotalRecord() > 0) {
				elderWallet = qrElderWallet.getResultList().get(0);
//				if (elderWallet.getWalletBalance() - form.getOfficialRent()-form.getOfficialPledge()<0) {
//					throwExp("钱包余额不足");	
//				}
				elderWallet.setWalletBalance(elderWallet.getWalletBalance() - form.getOfficialRent()-form.getOfficialPledge());// 扣掉钱包的钱
				elderPayRecord = costElderPayRecord(
						form.getLeaseId() == null || form.getLeaseId().equals("") ? "租赁" : "租赁续租", elder, 8,
						form.getLeaseId(), form.getOfficialRent()+form.getOfficialPledge(), 2,0,form.getCreateId());
			} else {
				throwExp("该老者尚未有钱包");
			}
		} else if (form.getPayWay() == 1) {// 如果是现金扣费
			elderPayRecord = costElderPayRecord(
					form.getLeaseId() == null || form.getLeaseId().equals("") ? "租赁" : "租赁续租", elder, 8,
					form.getLeaseId(), form.getOfficialPledge()+form.getOfficialRent(), 1,0,form.getCreateId());
		}
		else if(form.getPayWay()==3){//如果是五保免租金
			elderPayRecord = costElderPayRecord(
					form.getLeaseId() == null || form.getLeaseId().equals("") ? "租赁" : "租赁续租", elder, 8,
					form.getLeaseId(), form.getOfficialPledge(), 2,0,form.getCreateId());
		}
		
		leasePledge.setElderId(form.getElderId());

		YrLeaseSupply supply = null;

		leasePledge.setElderCardId(elder.getCardId());
		leasePledge.setElderName(elder.getName());
		leasePledge.setPledge(form.getPledge());
		leasePledge.setHandleId(form.getCreateId() == null ? "-1" : form.getCreateId());
		if (null != form.getCreateId()) {
			YrStaffInfo staffInfo = staffInfoService.findOne(form.getCreateId());
			if (null != staffInfo) {
				leasePledge.setHandleName(staffInfo.getName());
			}
		}
		leasePledge.setStatus(0);
		leasePledge.setLeaseSuppliesId(form.getLeaseSuppliesId());
		leasePledge.setLeaseRelationId(form.getLeaseId());
		supply = leaseSupplyService.findOne(form.getLeaseSuppliesId());
		if (null == supply) {
			throwExp("找不到租赁用品");
		}
		supply.setStockNumber(supply.getStockNumber() - 1);
		supply.setLeaseNumber(supply.getLeaseNumber() + 1);

		leasePledge.setLeaseSuppliesName(supply.getSuppliesName());
		leasePledge.setCreateId(form.getCreateId() == null ? "-1" : form.getCreateId());

//		if(form.getPayWay()!=4){//如果不是免租金押金
//			entity.setOfficialPledge(entity.getPledge());
//		}else{
//			entity.setOfficialPledge(Float.valueOf(0));
//		}
//		
		YrLeaseRentRecord leaseRentRecord  = new YrLeaseRentRecord();
		leaseRentRecord.setLeaseRentRecordId(UUIDGenerator.getUUID());
		leaseRentRecord.setCreateTime(new Date());
		leaseRentRecord.setCreateId(entity.getCreateId());
		leaseRentRecord.setElderId(entity.getElderId());
		leaseRentRecord.setLeaseType(entity.getLeaseType());
		leaseRentRecord.setType(2);//设置为新租类型  1新租2续租3退组
		leaseRentRecord.setSubjectRoomId(entity.getSubjectRoomId());
		leaseRentRecord.setOfficialRent(entity.getOfficialRent());
		leaseRentRecord.setTotalRent(entity.getTotalRent());
		leaseRentRecord.setPayWay(entity.getPayWay());
		leaseRentRecord.setLeaseId(entity.getLeaseId());
		leaseRentRecord.setPayTime(entity.getLeaseTime());
		leaseRentRecord.setLeaseStartTime(entity.getLeaseStartTime());
		leaseRentRecord.setLeaseEndTime(entity.getLeaseEndTime());
		
		Favorites favorites = new Favorites();
		if(form.getPayWay()!=4){//如果不是免租金押金
			favorites.putFavorite(YrLeasePledge.class, leasePledge);
		}
		favorites.putFavorite(YrLease.class, entity);
		favorites.putFavorite(YrElderWallet.class, elderWallet);
		favorites.putFavorite(YrElderPayRecord.class, elderPayRecord);
		favorites.putFavorite(YrLeaseSupply.class, supply);
		favorites.putFavorite(YrLeaseRentRecord.class, leaseRentRecord);

		selfService.addByFavorites(favorites);

		List<YrLeaseForm> formList = new ArrayList<YrLeaseForm>();
		formList.add(toForm(entity));
		result.setData(formList);
		return result;
	}

	/**
	 * 续租
	 * 
	 * @return
	 * @throws MyException
	 */
	@RequestMapping("addLease")
	@ResponseBody
	public HTTPResult<YrLeaseForm> addLease(String id, Integer days, Integer payType, Float totalFee,Float officialRent,String addTime,String createId)
			throws MyException {
		HTTPResult<YrLeaseForm> result = new HTTPResult<YrLeaseForm>();

		if (null == id || null == days || null == payType || null == totalFee || null==officialRent || null==addTime) {
			throwExp("参数有误");
		}
		SimpleDateFormat sdf = new SimpleDateFormat("YYYY-MM-dd");
		Date addLeaseTime = null;
		try {
			addLeaseTime = sdf.parse(addTime);
		} catch (ParseException e) {
			throwExp("续租时间格式有误！正确格式为：YYYY-MM-dd");
		}
		
		YrLease lease = selfService.findOne(id);
		if (null == lease) {
			throwExp("租赁信息不存在");
		}

		YrElder elder = elderService.findOne(lease.getElderId());
		if (null == elder) {
			throwExp("查询不到相关老者信息");
		}
		
		YrLeaseRentRecord leaseRentRecord  = new YrLeaseRentRecord();
		leaseRentRecord.setLeaseRentRecordId(UUIDGenerator.getUUID());
		leaseRentRecord.setCreateTime(new Date());
		leaseRentRecord.setCreateId(createId);
		leaseRentRecord.setElderId(lease.getElderId());
		leaseRentRecord.setLeaseType(lease.getLeaseType());
		leaseRentRecord.setType(1);//设置为新租类型  1新租2续租3退组
		leaseRentRecord.setSubjectRoomId(lease.getSubjectRoomId());
		leaseRentRecord.setOfficialRent(officialRent);
		leaseRentRecord.setTotalRent(totalFee);
		leaseRentRecord.setPayWay(payType);
		leaseRentRecord.setLeaseId(lease.getLeaseId());
		leaseRentRecord.setPayTime(addLeaseTime);
		leaseRentRecord.setLeaseStartTime(lease.getLeaseEndTime());
		
		lease.setLeaseEndTime(DateUtil.addDays(lease.getLeaseEndTime(), days));
		leaseRentRecord.setLeaseEndTime(lease.getLeaseEndTime());
		
		lease.setTotalRent(lease.getTotalRent() + totalFee);
		lease.setOfficialRent(lease.getOfficialRent()+officialRent);
		
		YrElderWallet elderWallet = null;
		YrElderPayRecord elderPayRecord = null;
		// 如果是钱包扣费
		if (payType == 2) {
			String sqlWhere = "elder_id=?1";
			QueryResult<YrElderWallet> qrElderWallet = elderWalletService.find(YrElderWallet.class, sqlWhere,
					new Object[] { lease.getElderId() });
			if (qrElderWallet.getTotalRecord() > 0) {
				elderWallet = qrElderWallet.getResultList().get(0);
				if (elderWallet.getWalletBalance() - officialRent < 0) {
					throwExp("钱包余额不足");
				}
				elderWallet.setWalletBalance(elderWallet.getWalletBalance() - officialRent);// 扣掉钱包的钱
				elderPayRecord = costElderPayRecord("租赁续租", elder, 8, lease.getLeaseId(), officialRent, payType,0,createId);
			} else {
				throwExp("该老者尚未有钱包");
			}
		} else if (payType == 1) {
			elderPayRecord = costElderPayRecord("租赁续租", elder, 8, lease.getLeaseId(), officialRent, payType,0,createId);
		}

		Favorites favorites = new Favorites();
		favorites.putFavorite(YrLease.class, lease);
		favorites.putFavorite(YrElderWallet.class, elderWallet);
		favorites.putFavorite(YrElderPayRecord.class, elderPayRecord);
		favorites.putFavorite(YrLeaseRentRecord.class, leaseRentRecord);
	
		selfService.addLease(favorites);
		
		return result;
	}

	/**
	 * 查看详情
	 * 
	 * @param id
	 *            主键
	 * @return
	 * @throws MyException
	 * @throws InstantiationException
	 * @throws IllegalAccessException
	 * @throws IllegalArgumentException
	 * @throws InvocationTargetException
	 */
	@RequestMapping("findDetail")
	@ResponseBody
	public HTTPResult<YrLeaseForm> findDetail(String id) throws MyException, InstantiationException,
			IllegalAccessException, IllegalArgumentException, InvocationTargetException {
		HTTPResult<YrLeaseForm> result = new HTTPResult<YrLeaseForm>();
		YrLease entity = selfService.findOne(id);

		YrLeaseForm form = ObjectUtils.objectToObject(entity, YrLeaseForm.class);

		String sqlWhere = "elder_id=?1 AND be_status<>2";
		QueryResult<YrElderBeHospital> qrElderBeHospital = elderBeHospitalService.find(YrElderBeHospital.class,
				sqlWhere, new Object[] { entity.getElderId() });

		if (qrElderBeHospital.getTotalRecord() > 0) {
			YrElderBeHospitalForm elderBeHospitalForm = ObjectUtils
					.objectToObject(qrElderBeHospital.getResultList().get(0), YrElderBeHospitalForm.class);
			form.setElderBeHospitalForm(elderBeHospitalForm);
		}

		QueryResult<YrElderWallet> qrElderWallet = elderWalletService.find(YrElderWallet.class, sqlWhere,
				new Object[] { entity.getElderId() });

		if (qrElderWallet.getTotalRecord() > 0) {
			form.setElderWalletForm(ObjectUtils.objectToObject(qrElderWallet.getResultList().get(0), YrElderWalletForm.class));
		}

		YrLeaseSupply leaseSupply = leaseSupplyService.findOne(entity.getLeaseSuppliesId());
		if (null != leaseSupply) {
			form.setLeaseSupplyForm(ObjectUtils.objectToObject(leaseSupply, YrLeaseSupplyForm.class));
		}

		YrElder elder = elderService.findOne(entity.getElderId());
		if (null != elder) {
			form.setElderForm(ObjectUtils.objectToObject(elder, YrElderForm.class));
		}

		YrStaffInfo staffInfo = staffInfoService.findOne(entity.getCreateId());
		if (null != staffInfo) {
			form.setRecorder(staffInfo.getName());
		}

		sqlWhere = "subject_room_id=?1 AND manager_of_subject_room=1 AND status=0";

		QueryResult<YrStaffInfo> qrStaffInfo = staffInfoService.find(YrStaffInfo.class, sqlWhere,
				new Object[] { qrElderBeHospital.getResultList().get(0).getSubjectRoomId() });
		if (qrStaffInfo.getTotalRecord() > 0) {
			form.setSubjectRoomManager(qrStaffInfo.getResultList().get(0).getName());
		}
		form.setTotalFee(form.getOfficialPledge()+form.getOfficialRent());//设置缴费合计
		
		List<YrLeaseForm> formList = new ArrayList<YrLeaseForm>();
		formList.add(form);
		result.setData(formList);

		return result;
	}

	/**
	 * 租赁用品退租
	 * 
	 * @param id
	 * @return
	 * @throws MyException
	 * @throws InvocationTargetException
	 * @throws IllegalArgumentException
	 * @throws IllegalAccessException
	 * @throws InstantiationException
	 */
	@RequestMapping("surrender")
	@ResponseBody
	public HTTPResult<YrLeaseForm> surrender(String id, Float returnMoney, Float payMoney,String createId,String returnTime,Integer payWay) throws MyException,
			InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
		HTTPResult<YrLeaseForm> result = new HTTPResult<YrLeaseForm>();

		if(null==id || null==returnMoney || null==payMoney || null==returnTime){
			throwExp("参数有误");
		}
		SimpleDateFormat sdf = new SimpleDateFormat("YYYY-MM-dd");
		Date returnLeaseTime = null;
		try {
			returnLeaseTime = sdf.parse(returnTime);
		} catch (ParseException e) {
			throwExp("续租时间格式有误！正确格式为：YYYY-MM-dd");
		}
		YrLease lease = selfService.findOne(id);
		lease.setLeaseStatus(2);
		lease.setReturnMoney(returnMoney);
		lease.setOffsetMoney(payMoney);
		lease.setReturnTime(new Date());

		YrElder elder = elderService.findOne(lease.getElderId());
		if (null == elder) {
			throwExp("查询不到相关老者信息");
		}

		YrLeaseSupply leaseSupply = leaseSupplyService.findOne(lease.getLeaseSuppliesId());
		if (null == leaseSupply) {
			throwExp("查不到相关租赁用品的信息");
		}
		leaseSupply.setStockNumber(leaseSupply.getStockNumber()+1);//将库存加1
		leaseSupply.setLeaseNumber(leaseSupply.getLeaseNumber()-1);//将出租数量-1
		// 新增一条退租用品记录
		YrRetreatLease retreatLease = ObjectUtils.objectToObject(leaseSupply, YrRetreatLease.class);

		retreatLease.setRetreatLeaseId(UUIDGenerator.getUUID());
		retreatLease.setStatus(0);
		retreatLease.setDisinfectStatus("未消毒");
		retreatLease.setLeaseNumber(1);// 出租数量
		retreatLease.setCreateTime(new Date());
		retreatLease.setCreateId("-1");
		retreatLease.setLeaseSuppliesId(leaseSupply.getLeaseSuppliesId());
		retreatLease.setElderId(lease.getElderId());

		String sqlWhere = "lease_relation_id = ?1";
		QueryResult<YrLeasePledge> qrLeasePledge = leasePledgeService.find(YrLeasePledge.class, sqlWhere,
				new Object[] { id });
		YrLeasePledge leasePledge = null;
		if (qrLeasePledge.getTotalRecord() > 0) {
			leasePledge = qrLeasePledge.getResultList().get(0);
			leasePledge.setStatus(1);//退掉押金
		}

		YrElderWallet elderWallet = null;
		YrElderPayRecord elderPayRecord = null;
		if (lease.getPayWay() == 2) {
			sqlWhere = "elder_id=?1";
			QueryResult<YrElderWallet> qrElderWallet = elderWalletService.find(YrElderWallet.class, sqlWhere,
					new Object[] { lease.getElderId() });
			if (qrElderWallet.getTotalRecord() > 0) {
				elderWallet = qrElderWallet.getResultList().get(0);
				if ((elderWallet.getWalletBalance() + returnMoney - payMoney) < 0) {
					throwExp("钱包余额不足");
				}
				elderWallet.setWalletBalance(elderWallet.getWalletBalance() + returnMoney - payMoney);// 返回钱包的钱
				elderPayRecord = costElderPayRecord("租赁退租", elder, 8, lease.getLeaseId(),payMoney-returnMoney ,2,0,createId);
			} else {
				throwExp("该老者尚未有钱包");
			}
		}
		YrLeaseRentRecord leaseRentRecord  = null;
		
		Float tpPay = payMoney>0?payMoney+lease.getOfficialPledge():lease.getOfficialPledge()-returnMoney;
		if(tpPay>0||tpPay<0){
			leaseRentRecord  = new YrLeaseRentRecord();
			leaseRentRecord.setLeaseRentRecordId(UUIDGenerator.getUUID());
			leaseRentRecord.setCreateTime(new Date());
			leaseRentRecord.setCreateId(createId);
			leaseRentRecord.setElderId(lease.getElderId());
			leaseRentRecord.setLeaseType(lease.getLeaseType());
			leaseRentRecord.setType(3);//设置为新租类型  1新租2续租3退组
			leaseRentRecord.setSubjectRoomId(lease.getSubjectRoomId());
			leaseRentRecord.setOfficialRent(tpPay);
			leaseRentRecord.setTotalRent(tpPay);
			leaseRentRecord.setPayWay(tpPay>0?2:payWay);
			leaseRentRecord.setLeaseId(lease.getLeaseId());
			leaseRentRecord.setPayTime(returnLeaseTime);
			leaseRentRecord.setLeaseStartTime(null);
			leaseRentRecord.setLeaseEndTime(null);
		}

		Favorites favorites = new Favorites();

		favorites.putFavorite(YrLease.class, lease);
		favorites.putFavorite(YrRetreatLease.class, retreatLease);
		favorites.putFavorite(YrLeasePledge.class, leasePledge);
		favorites.putFavorite(YrElderWallet.class, elderWallet);
		favorites.putFavorite(YrElderPayRecord.class, elderPayRecord);
		favorites.putFavorite(YrLeaseSupply.class, leaseSupply);
		favorites.putFavorite(YrLeaseRentRecord.class,leaseRentRecord);

		selfService.executeSurrender(favorites);

		return result;

	}

	/**
	 * 退租时查询租赁信息
	 * 
	 * @param searchVal
	 * @return
	 * @throws MyException
	 * @throws InstantiationException
	 * @throws IllegalAccessException
	 * @throws IllegalArgumentException
	 * @throws InvocationTargetException
	 */
	@RequestMapping("find")
	@ResponseBody
	public HTTPResult<YrLeaseDetailForm> find(String searchVal) throws MyException, InstantiationException,
			IllegalAccessException, IllegalArgumentException, InvocationTargetException {
		HTTPResult<YrLeaseDetailForm> result = new HTTPResult<YrLeaseDetailForm>();
		YrLeaseDetailForm form = new YrLeaseDetailForm();
		String sqlWhere = "name=?1 OR card_id=?2";
		QueryResult<YrElder> qrElder = elderService.find(YrElder.class, sqlWhere,
				new Object[] { searchVal, searchVal });
		if (qrElder.getTotalRecord() == 0) {
			throwExp("查不到相关的老者信息");
		}
		YrElder elder = qrElder.getResultList().get(0);

		sqlWhere = "elder_id=?1 AND be_status<>2";

		QueryResult<YrElderBeHospital> qrElderBeHospital = elderBeHospitalService.find(YrElderBeHospital.class,
				sqlWhere, new Object[] { elder.getElderId() });

		if (qrElderBeHospital.getTotalRecord() > 0) {
			YrElderBeHospitalForm elderBeHospitalForm = ObjectUtils
					.objectToObject(qrElderBeHospital.getResultList().get(0), YrElderBeHospitalForm.class);

			YrStaffInfo staffInfo = staffInfoService.findOne(elderBeHospitalForm.getCreateId());
			if (null != staffInfo) {
				elderBeHospitalForm.setRecorder(staffInfo.getName());
			}
			form.setElderBeHospitalForm(elderBeHospitalForm);
		}

		// QueryResult<YrElderWallet> qrElderWallet =
		// elderWalletService.find(YrElderWallet.class, sqlWhere,new
		// Object[]{elder.getElderId()});
		//
		// if(qrElderWallet.getTotalRecord()>0){
		// YrElderWalletForm elderWalletForm =
		// ObjectUtils.objectToObject(qrElderWallet.getResultList().get(0),YrElderWalletForm.class);
		// form.setElderWalletForm(elderWalletForm);
		// }

		if (null != elder) {
			form.setElderForm(ObjectUtils.objectToObject(elder, YrElderForm.class));
		}

		sqlWhere = "elder_id=?1 AND lease_status=1";

		QueryResult<YrLease> qrLease = selfService.find(YrLease.class, sqlWhere, new Object[] { elder.getElderId() });
		List<YrLeaseForm> leaseForms = new ArrayList<YrLeaseForm>();
		for (YrLease lease : qrLease.getResultList()) {
			YrLeaseForm leaseForm = ObjectUtils.objectToObject(lease, YrLeaseForm.class);
			YrLeaseSupply leaseSupply = leaseSupplyService.findOne(lease.getLeaseSuppliesId());
			if (null != leaseSupply) {
				leaseForm.setLeaseSupplyForm(ObjectUtils.objectToObject(leaseSupply, YrLeaseSupplyForm.class));
			}
			leaseForms.add(leaseForm);
		}

		form.setLeaseForms(leaseForms);

		List<YrLeaseDetailForm> formList = new ArrayList<YrLeaseDetailForm>();
		formList.add(form);
		result.setData(formList);

		return result;

	}
	
	@RequestMapping("findLeaseRecord")
	@ResponseBody
	public HTTPResult<YrLeaseForm> findLeaseRecord(String dateSince,String dateEnd,Integer leaseStatus) throws Exception{
		HTTPResult<YrLeaseForm> result = new HTTPResult<YrLeaseForm>();
		
		String sqlWhere = "";
		QueryResult<YrLease> qr  = null;
		
		if(leaseStatus==null){
			sqlWhere = "DATE_FORMAT(lease_time,'%Y-%m-%d')>=?1 AND DATE_FORMAT(lease_time,'%Y-%m-%d')<=?2";
			qr = selfService.find(YrLease.class, sqlWhere, new Object[]{dateSince,dateEnd});
		}else{
			sqlWhere = "DATE_FORMAT(lease_time,'%Y-%m-%d')>=?1 AND DATE_FORMAT(lease_time,'%Y-%m-%d')<=?2 AND leaseStatus=?3";
			qr = selfService.find(YrLease.class, sqlWhere, new Object[]{dateSince,dateEnd,leaseStatus});
		}
		
		List<YrLeaseForm> formList = new ArrayList<YrLeaseForm>();
		for(YrLease entity : qr.getResultList()){
			YrLeaseForm form = toForm(entity);
			YrElder elder = elderService.findOne(entity.getElderId());
			if(null!=elder){
				form.setElderForm(ObjectUtils.objectToObject(elder,YrElderForm.class));
			}
			YrLeaseSupply supply = leaseSupplyService.findOne(entity.getLeaseSuppliesId());
			if(null!=supply){
				form.setLeaseSupplyForm(ObjectUtils.objectToObject(supply, YrLeaseSupplyForm.class));
			}
			form.setTotalFee((form.getOfficialPledge()==null?0:form.getOfficialPledge())+(form.getOfficialRent()==null?0:form.getOfficialRent()));//这是缴费合计
			formList.add(form);
		}
		
		result.setData(formList);
		return result;
	}
	
	/**
	 * 构造一个老者缴费记录
	 * 
	 * @return
	 * @throws MyException 
	 */
	public YrElderPayRecord costElderPayRecord(String decs, YrElder elder, Integer costType, String relationId,
			Float money,Integer payWay,Integer payType,String createId) throws MyException {
		YrElderPayRecord elderPayRecord = new YrElderPayRecord();
		if(elder.getElderType()==1){//如果是院内老人
			String sqlWhere = "elder_id=?1 AND be_status<>2";
			QueryResult<YrElderBeHospital> qrElderBeHospital = elderBeHospitalService.find(YrElderBeHospital.class,sqlWhere, new Object[]{elder.getElderId()});
			if(qrElderBeHospital.getResultList().isEmpty()){
				throwExp("查询不到老者的相关住院信息");
			}
			elderPayRecord.setSubjectRoomId(qrElderBeHospital.getResultList().get(0).getSubjectRoomId());
			elderPayRecord.setBeHospitalId(qrElderBeHospital.getResultList().get(0).getBeHospitalId());
		}else {
			elderPayRecord.setSubjectRoomId("-1");
			elderPayRecord.setBeHospitalId("-1");
		}
		elderPayRecord.setElderPayRecordId(UUIDGenerator.getUUID());
		elderPayRecord.setCostDesc(decs);
		elderPayRecord.setPayDate(new Date());
		elderPayRecord.setElderId(elder.getElderId());
		elderPayRecord.setElderCardId(elder.getCardId());
		elderPayRecord.setElderName(elder.getName());
		elderPayRecord.setPayStatus(1);
		elderPayRecord.setPayWay(payWay);
		elderPayRecord.setCostType(costType);
		elderPayRecord.setCreateTime(new Date());
		elderPayRecord.setRelationId(relationId);
		elderPayRecord.setPayMoney(money);
		elderPayRecord.setPayType(payType);
		elderPayRecord.setCreateId(createId);
		return elderPayRecord;
	}

	@Override
	public YrLeaseForm toForm(YrLease e) throws Exception {
		YrLeaseForm form = ObjectUtils.objectToObject(e, YrLeaseForm.class);
		return form;
	}

	@Override
	public YrLease toEntity(YrLeaseForm f) throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

}
